from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class GetAdvice(webapp.RequestHandler):
    """ Suggestion for popular keywords AJAX class """

    def get(self):
        self.response.headers['Content-Type'] = 'application/json'

        if self.request.method == 'GET':
            data=self.request.GET.copy()
            categoryName=data.get("categoryname")
            retAdvice=[]
            for i in range (0,6):
                retAdvice.append("")
                
            # Get selected category
            q_1 = db.GqlQuery("SELECT * FROM StocksCategories WHERE category = :1",categoryName)
            if q_1.count()==0:
                self.response.out.write(simplejson.dumps({'status': 'error'}))
            else:
                q_2 = db.GqlQuery("SELECT * FROM StocksData WHERE categoryref = :1 LIMIT 0,6",q_1.fetch(1)[0])
                i=0
                for stock in q_2:
                    retAdvice[i]=stock.stockname
                    i+=1
                    if i==6:
                        break;
            
            self.response.out.write(simplejson.dumps(
            {'status': 'success', 
            'retAdvice':[retAdvice[0],retAdvice[1],retAdvice[2], retAdvice[3], retAdvice[4], retAdvice[5]],
            'count': i}))
        else:
            self.response.out.write(simplejson.dumps({'status': 'error'}))


application = webapp.WSGIApplication(
                                     [('/ajax/buyadvice', GetAdvice)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
